import React, { FC, useCallback } from "react";
import { componentConfigGroup, ComponentConfigType } from "../../../questionComponents";
import { Typography } from "antd";
import classNames from "classnames/bind";
import style from "./index.module.scss";
import { useDispatch } from "react-redux";
import { addComponent } from "../../../store/componentReducer";
const CBN = classNames.bind(style);

const { Title } = Typography;

function getComponent(c: ComponentConfigType, index: number) {
  const { title, type, Component, defaultValue } = c;
  const dispatch = useDispatch();
  // 使用useCallback进行缓存 不依赖任何的State
  const handleClick = useCallback(() => {
    dispatch(
      addComponent({
        fe_id: String(Math.floor(Math.random() * 100000000)).padStart(8, "0"),
        title,
        type,
        islock: false,
        ishidden: false,
        props: defaultValue,
      }),
    );
  }, []);
  // function handleClick() {
  //   dispatch(
  //     addComponent({
  //       fe_id: String(Math.floor(Math.random() * 100000000)).padStart(8, "0"),
  //       title,
  //       type,
  //       islock: false,
  //       ishidden: false,
  //       props: defaultValue,
  //     }),
  //   );
  // }

  return (
    <div key={index} className={CBN("wrapper")} onClick={handleClick}>
      <div className={CBN("component")}>
        <Component></Component>
      </div>
    </div>
  );
}
const ComponentLib: FC = () => {
  return (
    <div className={CBN("ComponentLib")}>
      {componentConfigGroup.map((item, index) => {
        const { groupName, components } = item;
        return (
          <div key={index} style={{ padding: " 0 10px" }}>
            <Title level={3} style={{ fontSize: "16px", marginTop: index != 0 ? "14px" : "0" }}>
              {groupName}
            </Title>
            {components.map((c, index) => {
              return getComponent(c, index);
            })}
          </div>
        );
      })}
    </div>
  );
};

export default ComponentLib;
